package org.whatever.aha.zjut.platform.controller.school;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaMode;
import cn.dev33.satoken.stp.StpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.whatever.aha.zjut.base.constant.AuthConst;
import org.whatever.aha.zjut.base.constant.ErrorCode;
import org.whatever.aha.zjut.base.constant.MsgTypeRedisConstant;
import org.whatever.aha.zjut.base.constant.StatusConstant;
import org.whatever.aha.zjut.base.dto.AjaxResult;
import org.whatever.aha.zjut.base.exception.AppException;
import org.whatever.aha.zjut.platform.annotation.CheckModifyQuota;
import org.whatever.aha.zjut.platform.annotation.StageLimit;
import org.whatever.aha.zjut.platform.dto.school.ProjectToNextStageDto;
import org.whatever.aha.zjut.platform.entity.competition.AcademyCompetition;
import org.whatever.aha.zjut.platform.entity.competition.Competition;
import org.whatever.aha.zjut.platform.entity.project.Project;
import org.whatever.aha.zjut.platform.message.MessageService;
import org.whatever.aha.zjut.platform.service.AcademyAdminService;
import org.whatever.aha.zjut.platform.service.competition.AcademyCompetitionService;
import org.whatever.aha.zjut.platform.service.competition.CompetitionService;
import org.whatever.aha.zjut.platform.service.competition.CompetitionStageStatusService;
import org.whatever.aha.zjut.platform.service.project.ProjectService;
import org.whatever.aha.zjut.platform.service.school.ProjectScoreService;
import org.whatever.aha.zjut.platform.vo.school.AcademyCompetitionRoughInfoVo;
import org.whatever.aha.zjut.platform.vo.school.DirectProvinceInfoVo;
import org.whatever.aha.zjut.platform.vo.school.SchoolRecInfoVo;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

/**
 * @author Vc
 * @version 1.0
 * @Desc 推荐项目审核相关接口
 * @date 2021/11/07 11:24
 */
@Api(tags = "校级管理员项目管理类")
@RequestMapping("/v1/school/projectJudge")
@RequiredArgsConstructor
@RestController
@Validated
@SaCheckRole(value = {AuthConst.R_supper, AuthConst.R_school}, mode = SaMode.OR)
public class RecommendProjectJudgeController {
    final AcademyCompetitionService academyCompetitionService;
    final CompetitionService competitionService;
    final ProjectService projectService;
    final AcademyAdminService academyAdminService;
    final CompetitionStageStatusService competitionStageStatusService;
    final MessageService messageService;
    final ProjectScoreService projectScoreService;

    @ApiOperation("获得推荐项目审核粗略信息")
    @GetMapping("/getRecommendProjectRough/{compId}/{stageId}")
    public AjaxResult<Map> getRecommendProjectRough(@PathVariable("compId")int compId, @PathVariable("stageId")int stageId) {
        SchoolRecInfoVo schoolRecInfoVo = competitionService.getSchoolRecInfoVo(compId, stageId);
        DirectProvinceInfoVo directProvinceInfoVo = academyCompetitionService.getDirectProvinceInfoVo(stageId);
        List<AcademyCompetitionRoughInfoVo> academyCompetitionRoughInfoVoList = academyCompetitionService.getAcademyCompetitionRoughInfoVoList(compId, stageId);
        return AjaxResult.SUCCESS(Map.of("schoolRecInfoVo",schoolRecInfoVo,"directProvinceInfoVo",directProvinceInfoVo,"academyCompetitionRoughInfoVoList",academyCompetitionRoughInfoVoList));
    }

    @CheckModifyQuota
    @StageLimit({"submit", "judge"})
    @ApiOperation("修改直推省级数量")
    @PutMapping("/modifyAcademyProvinceRecAmt/{academyId}/{compId}/{stageId}")
    public AjaxResult<Integer> modifyProvinceRecAmt(@PathVariable("academyId")int academyId,
                                                    @PathVariable("compId")int compId,
                                                    @PathVariable("stageId")int stageId,
                                                    @RequestParam(value = "quota", required = true)int quota) {
        AcademyCompetition academyCompetitionById = academyCompetitionService.getAcademyCompetitionById(academyId, stageId);
        academyCompetitionById.setAcademyProvinceRecAmt(quota);
        return AjaxResult.SUCCESS(academyCompetitionService.updateAcademyCompetition(academyCompetitionById));
    }

    @CheckModifyQuota
    @StageLimit({"submit", "judge"})
    @ApiOperation("修改院级三等奖数量")
    @PutMapping("/modifyAcademyThirdPrize/{academyId}/{compId}/{stageId}")
    public AjaxResult<Integer> modifyAcademyThirdPrize(@PathVariable("academyId")int academyId,
                                                       @PathVariable("compId")int compId,
                                                       @PathVariable("stageId")int stageId,
                                                       @RequestParam(value = "quota", required = true)int quota) {
        AcademyCompetition academyCompetitionById = academyCompetitionService.getAcademyCompetitionById(academyId, stageId);
        academyCompetitionById.setThirdPrizeAmt(quota);
        return AjaxResult.SUCCESS(academyCompetitionService.updateAcademyCompetition(academyCompetitionById));
    }


    @StageLimit({"submit", "judge"})
    @ApiOperation("修改校团委可推荐数量")
    @PutMapping("/modifySchoolCommunityRecNum/{compId}")
    public AjaxResult<Integer> modifySchoolCommunityRecNum(@PathVariable("compId")int compId,
                                                       @RequestParam(value = "quota", required = true)int quota) {
        Competition competitionById = competitionService.getCompetitionById(compId);
        if(competitionById.getCompSchoolRecAmt() > quota){
            throw new AppException(ErrorCode.SCHOOL_ACADEMY_MODIFY_QUOTA_INVALID);
        }
        competitionById.setCompSchoolRecAmt(quota);
        return AjaxResult.SUCCESS(competitionService.updateCompById(competitionById));
    }

    @CheckModifyQuota
    @StageLimit({"submit", "judge"})
    @ApiOperation("修改学院普通推荐数量")
    @PutMapping("/modifyAcademyRecNum/{academyId}/{compId}/{stageId}")
    public AjaxResult<Integer> modifyAcademyRecNum(@PathVariable("academyId")int academyId,
                                                   @PathVariable("compId")int compId,
                                                   @PathVariable("stageId")int stageId,
                                                   @RequestParam(value = "quota", required = true)int quota) {
        AcademyCompetition academyCompetitionById = academyCompetitionService.getAcademyCompetitionById(academyId, stageId);
        academyCompetitionById.setAcademyRecAmt(quota);
        return AjaxResult.SUCCESS(academyCompetitionService.updateAcademyCompetition(academyCompetitionById));
    }

    @StageLimit({"submit", "judge"})
    @ApiOperation("退回修改给学生")
    @PutMapping("/SchoolReturnModify/{projectId}/{compId}")
    @Transactional(rollbackFor = Exception.class, propagation= Propagation.REQUIRED)
    public AjaxResult<Integer> SchoolReturnModify(@PathVariable("projectId")int projectId,
                                                  @PathVariable("compId")int compId,
                                                  @RequestBody String comment){
        int userId = StpUtil.getLoginIdAsInt();
        if(projectScoreService.getJudgeResultStu(projectId).size()>0){
            throw new AppException(ErrorCode.SCHOOL_RETURN_FOR_MODIFY_NOT_QUALIFY);
        }
        Project project = projectService.getProjectById(projectId);
        int affectRow = projectService.SchoolReturnModify(projectId, comment, userId);
        SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sendTime = s.format(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime());
        messageService.createUserMessage(StatusConstant.MSG_SYS_SENDER.getCode(), project.getProjectLeaderId(), sendTime,
                MsgTypeRedisConstant.MSG_TYPE_PROJECT_RETURN_TITLE, MsgTypeRedisConstant.getKeyProjectReturn(project.getProjectName(), "校级管理员", comment),
                MsgTypeRedisConstant.MSG_SYS_NAME, StatusConstant.MSG_TYPE_PROJECT_RETURN.getCode());
        return AjaxResult.SUCCESS(affectRow);
    }

    @ApiOperation("获得普通推荐项目")
    @GetMapping("/getWaitingForJudgeProjectInfo/{academyId}/{compId}/{stageId}")
    public AjaxResult<Map> getWaitingForJudgeProjectInfo(@PathVariable("academyId")int academyId,
                                                         @PathVariable("compId")int compId,
                                                         @PathVariable("stageId")int stageId,
                                                         @RequestParam(value = "pageNum", required = true, defaultValue = "1") int pageNum,
                                                         @RequestParam(value = "pageSize", required = true, defaultValue = "10") int pageSize){
        return AjaxResult.SUCCESS(projectService.getWaitingForJudgeProjectInfo(academyId, compId, stageId, pageNum, pageSize));
    }

    @ApiOperation("获取校团委推荐项目")
    @GetMapping("/getSchoolCommunityRecProjectInfo/{compId}/{stageId}")
    public AjaxResult<Map> getSchoolCommunityRecProjectInfo(@PathVariable(value = "compId") int compId,
                                                            @PathVariable("stageId")int stageId,
                                                            @RequestParam(value = "pageNum", required = true, defaultValue = "1") int pageNum,
                                                            @RequestParam(value = "pageSize", required = true, defaultValue = "10") int pageSize){
        return AjaxResult.SUCCESS(projectService.getSchoolCommunityRecProjectInfo(compId, stageId, pageNum, pageSize));
    }

    @ApiOperation("获取省级直推推荐项目")
    @GetMapping("/getProvinceRecProjectInfo/{compId}/{stageId}")
    public AjaxResult<Map> getProvinceRecProjectInfo(@PathVariable(value = "compId") int compId,
                                                     @PathVariable("stageId")int stageId,
                                                     @RequestParam(value = "pageNum", required = true, defaultValue = "1") int pageNum,
                                                     @RequestParam(value = "pageSize", required = true, defaultValue = "10") int pageSize){
        return AjaxResult.SUCCESS(projectService.getProvinceRecProjectInfo(compId, stageId, pageNum, pageSize));
    }

    @StageLimit({"submit", "judge"})
    @ApiOperation("批量审核项目")
    @PutMapping("/judgeProjects/{compId}")
    public AjaxResult<Integer> judgeProjects(@PathVariable("compId")int compId, @RequestParam String projectIds){
        return AjaxResult.SUCCESS(projectService.judgeProjects(projectIds.split("-")));
    }

    @StageLimit({"judge", "public"})
    @ApiOperation("批量增加推荐项目进入下一个阶段")
    @PutMapping("/recProjectNextStageInBatch/{stageId}")
    public AjaxResult<Integer> recProjectNextStageInBatch(@PathVariable("stageId")int stageId, @RequestBody ProjectToNextStageDto projectIds){
        Integer affectRow = projectService.recProjectNextStageInBatch(projectIds.getProjectIds());
        SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sendTime = s.format(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime());
        projectIds.getProjectIds().stream().forEach(projectId -> {
            messageService.createUserMessage(StatusConstant.MSG_SYS_SENDER.getCode(), projectId, sendTime,
                    MsgTypeRedisConstant.MSG_TYPE_ENTER_NEXT_STAGE_TITLE, MsgTypeRedisConstant.getKeyEnterNextStage(projectService.getProjectNameById(projectId)),
                    MsgTypeRedisConstant.MSG_SYS_NAME, StatusConstant.MSG_TYPE_PROJECT_ENTER_NEXT_STAGE.getCode());
        });
        return AjaxResult.SUCCESS(affectRow);
    }


}
